<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理员登录 - 学术助手</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .login-bg {
            background: linear-gradient(135deg, #f8fafc 0%, #e2e8f0 100%);
        }
        
        .login-card {
            background: white;
            box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
        }
        
        .fade-in {
            animation: fadeIn 0.5s ease-out;
        }
        
        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(20px); }
            to { opacity: 1; transform: translateY(0); }
        }
        
        .shake {
            animation: shake 0.5s ease-in-out;
        }
        
        @keyframes shake {
            0%, 100% { transform: translateX(0); }
            25% { transform: translateX(-5px); }
            75% { transform: translateX(5px); }
        }
        
        .input-focus:focus {
            box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
        }
    </style>
</head>
<body class="login-bg min-h-screen flex items-center justify-center">
    <!-- 登录表单 -->
    <div class="login-card rounded-lg p-8 w-full max-w-md fade-in">
        <!-- 头部 -->
        <div class="text-center mb-8">
            <div class="inline-flex items-center justify-center w-16 h-16 bg-blue-600 rounded-lg mb-4">
                <i class="fas fa-graduation-cap text-white text-2xl"></i>
            </div>
            <h1 class="text-2xl font-bold text-gray-900 mb-2">学术助手</h1>
            <p class="text-gray-600">管理员登录</p>
        </div>

        <!-- 登录表单 -->
        <form id="loginForm" class="space-y-6">
            <div>
                <label for="username" class="block text-sm font-medium text-gray-700 mb-2">
                    用户名
                </label>
                <input type="text" id="username" name="username" required 
                       class="input-focus w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                       placeholder="请输入用户名">
            </div>

            <div>
                <label for="password" class="block text-sm font-medium text-gray-700 mb-2">
                    密码
                </label>
                <div class="relative">
                    <input type="password" id="password" name="password" required 
                           class="input-focus w-full px-4 py-3 pr-12 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-colors"
                           placeholder="请输入密码">
                    <button type="button" id="togglePassword" class="absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-500 hover:text-gray-700">
                        <i class="fas fa-eye" id="eyeIcon"></i>
                    </button>
                </div>
            </div>

            <!-- 错误提示 -->
            <div id="errorMessage" class="hidden bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg">
                <div class="flex items-center">
                    <i class="fas fa-exclamation-circle mr-2"></i>
                    <span id="errorText"></span>
                </div>
            </div>

            <!-- 登录按钮 -->
            <button type="submit" id="loginBtn" 
                    class="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-4 rounded-lg transition-colors focus:ring-2 focus:ring-blue-500 focus:ring-offset-2">
                <i class="fas fa-sign-in-alt mr-2"></i>登录
            </button>
        </form>

        <!-- 底部链接 -->
        <div class="mt-6 text-center">
            <a href="index.html" class="text-blue-600 hover:text-blue-700 text-sm transition-colors">
                <i class="fas fa-arrow-left mr-1"></i>返回首页
            </a>
        </div>
    </div>

    <script>
        class LoginManager {
            constructor() {
                this.init();
            }

            init() {
                this.bindEvents();
                this.checkExistingLogin();
            }

            bindEvents() {
                // 表单提交
                document.getElementById('loginForm').addEventListener('submit', (e) => {
                    e.preventDefault();
                    this.handleLogin();
                });

                // 密码显示/隐藏
                document.getElementById('togglePassword').addEventListener('click', () => {
                    this.togglePasswordVisibility();
                });

                // 回车键登录
                document.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter') {
                        const form = document.getElementById('loginForm');
                        if (document.activeElement.closest('form') === form) {
                            e.preventDefault();
                            this.handleLogin();
                        }
                    }
                });
            }

            // 检查是否已登录
            checkExistingLogin() {
                const token = localStorage.getItem('adminToken');
                if (token) {
                    // 验证token是否有效
                    this.verifyToken(token);
                }
            }

            // 验证token
            async verifyToken(token) {
                try {
                    const response = await fetch('/api/admin/verify', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ token })
                    });

                    const result = await response.json();
                    if (result.success) {
                        // token有效，直接跳转到管理页面
                        window.location.href = 'admin.html';
                    } else {
                        // token无效，清除本地存储
                        localStorage.removeItem('adminToken');
                    }
                } catch (error) {
                    console.error('Token验证失败:', error);
                    localStorage.removeItem('adminToken');
                }
            }

            // 处理登录
            async handleLogin() {
                const username = document.getElementById('username').value.trim();
                const password = document.getElementById('password').value.trim();

                if (!username || !password) {
                    this.showError('请输入用户名和密码');
                    return;
                }

                const loginBtn = document.getElementById('loginBtn');
                const originalText = loginBtn.innerHTML;
                loginBtn.disabled = true;
                loginBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i>登录中...';

                try {
                    const response = await fetch('/api/admin/login', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({ username, password })
                    });

                    const result = await response.json();

                    if (response.ok && result.success) {
                        // 登录成功
                        localStorage.setItem('adminToken', result.token);
                        this.showSuccess('登录成功，正在跳转...');
                        
                        setTimeout(() => {
                            window.location.href = 'admin.html';
                        }, 1000);
                    } else {
                        // 登录失败
                        this.showError(result.message || '登录失败，请检查用户名和密码');
                        this.shakeForm();
                    }
                } catch (error) {
                    console.error('登录请求失败:', error);
                    this.showError('网络错误，请稍后重试');
                    this.shakeForm();
                } finally {
                    loginBtn.disabled = false;
                    loginBtn.innerHTML = originalText;
                }
            }

            // 切换密码可见性
            togglePasswordVisibility() {
                const passwordInput = document.getElementById('password');
                const eyeIcon = document.getElementById('eyeIcon');

                if (passwordInput.type === 'password') {
                    passwordInput.type = 'text';
                    eyeIcon.className = 'fas fa-eye-slash';
                } else {
                    passwordInput.type = 'password';
                    eyeIcon.className = 'fas fa-eye';
                }
            }

            // 显示错误信息
            showError(message) {
                const errorDiv = document.getElementById('errorMessage');
                const errorText = document.getElementById('errorText');
                
                errorDiv.className = 'bg-red-50 border border-red-200 text-red-700 px-4 py-3 rounded-lg';
                errorText.textContent = message;
                errorDiv.classList.remove('hidden');
                
                // 3秒后自动隐藏
                setTimeout(() => {
                    errorDiv.classList.add('hidden');
                }, 3000);
            }

            // 显示成功信息
            showSuccess(message) {
                const errorDiv = document.getElementById('errorMessage');
                const errorText = document.getElementById('errorText');
                
                errorDiv.className = 'bg-green-50 border border-green-200 text-green-700 px-4 py-3 rounded-lg';
                errorText.textContent = message;
                errorDiv.classList.remove('hidden');
            }

            // 表单震动效果
            shakeForm() {
                const form = document.querySelector('.login-card');
                form.classList.add('shake');
                setTimeout(() => {
                    form.classList.remove('shake');
                }, 500);
            }
        }

        // 初始化登录管理器
        document.addEventListener('DOMContentLoaded', () => {
            new LoginManager();
        });
    </script>
</body>
</html>